package com.zjlanyun.eplus.view.report.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.zjlanyun.eplus.R;
import com.zjlanyun.eplus.network.WebApi;
import com.zjlanyun.eplus.nohttp.HttpRequest;
import com.zjlanyun.eplus.nohttp.SimpleHttpListener;
import com.zjlanyun.eplus.view.report.adapter.MyListViewAdapter;
import com.zjlanyun.eplus.view.report.adapter.showBean;
import com.zjlanyun.eplus.view.report.custom.XListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_ACTION;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_FCARTOGRAMTYPR;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_FCORRESPONDINGTABLE;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_FLISTID;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_FXVALUE;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_FYVALUE;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_JSON_DATA;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_JSON_LF_CONDITION;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_JSON_LF_LISTSIZE;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_JSON_LF_LISTVAR;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_LF_PAGE;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_LF_PAGESIZE;
import static com.zjlanyun.eplus.view.report.UtilConstants.LISTFRAGMENT_ACTION;
import static com.zjlanyun.eplus.view.report.UtilConstants.LOAD_MORE;
import static com.zjlanyun.eplus.view.report.UtilConstants.MODEL_ID;
import static com.zjlanyun.eplus.view.report.UtilConstants.NO_MORE;
import static com.zjlanyun.eplus.view.report.UtilConstants.PAGE_COUNTS;
import static com.zjlanyun.eplus.view.report.UtilConstants.SQL_CONDITION;


/**
 * 作者：韩笑 on 2017/6/26 0026 13:20
 * <p>
 * 作用：列表布局Fragment
 */


public class ListFragment extends Fragment implements XListView.IXListViewListener{
    private static final String TAG = "ListFragment";

    private String modelId = null;//模型id
    private String sql = null;//条件

    //加载，刷新的ListView
    private XListView mListView;

    //分页设置
    private int PAGE = 1;//当前页
    private int TOTAL_PAGE = 10;//总页数

    //ListView显示数据
    private MyListViewAdapter adapter;
    private List<List<showBean>> refreshList;
    private int[] coumId;
    private List<List<showBean>> showList;
    private List<Integer> typeList;//代表listview长度


    public static ListFragment newInstance(String modelId, String sql) {
        Bundle args = new Bundle();
        ListFragment fragment = new ListFragment();
        args.putString(MODEL_ID, modelId);
        args.putString(SQL_CONDITION, sql);
        fragment.setArguments(args);
        return fragment;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.list_fragment, null);
        Log.d(TAG, "modelId:" + getArguments().getString(MODEL_ID) + ".sql:" + getArguments().getString(SQL_CONDITION));
        modelId = getArguments().getString(MODEL_ID);
        sql = getArguments().getString(SQL_CONDITION);
        initView(view);
        return view;
    }

    /**
     * 初始化
     * @param view
     */
    public void initView(View view){
        mListView = (XListView)view.findViewById(R.id.xListView);
        mListView.setPullLoadEnable(true);
        mListView.setXListViewListener(this);
        showList = new ArrayList<>();//展示数据的数据list
        initData(LISTFRAGMENT_ACTION,modelId,PAGE ,false,sql);
    }

    /**
     * 停止动画
     */
    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setFootMsg(LOAD_MORE);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        mListView.setRefreshTime(df.format(new Date()));
    }

    /**
     * IXListViewListener中onRefresh 刷新
     */
    @Override
    public void onRefresh() {
        Log.d(TAG, "eyeView.startAnimate();");
        //当执行下拉刷新操作是，将页数重置为1
        PAGE = 1;
        initData(LISTFRAGMENT_ACTION,modelId,PAGE,true,sql);
        onLoad();
    }

    /**
     * IXListViewListener中onLoadMore 加载更多
     */
    @Override
    public void onLoadMore() {
        Log.d(TAG,"PAGE ==="+PAGE+"TOTAL_PAGE ==="+TOTAL_PAGE);
        //下拉刷新
        if (PAGE >= TOTAL_PAGE){ //当 当前页 >= 总页数时，不在请求数据
            Log.d(TAG,"没有更多内容了");
            onLoad();
            mListView.setFootMsg(NO_MORE);
        }else {
            PAGE++;
            Log.d(TAG, "下拉加载，当前PAGE：" + PAGE + "/总页数：" + TOTAL_PAGE);
            initData(LISTFRAGMENT_ACTION, modelId, PAGE, false,sql);
        }
    }



    /**
     * 获取数量
     * @param arg0 操作
     * @param arg1 模型id
     * @param page 当前页数
     * @param isRefresh 操作是否为下拉刷新
     */
    public void initData(String arg0,String arg1,int page,final boolean isRefresh,String sql){
        HttpRequest client = new HttpRequest(getActivity(), WebApi.api());
        client.getRequest().add(KEY_ACTION, arg0);
        client.getRequest().add(MODEL_ID, arg1);
        client.getRequest().add(KEY_LF_PAGE, page);
        client.getRequest().add(KEY_LF_PAGESIZE, PAGE_COUNTS);
        client.getRequest().add(SQL_CONDITION, sql);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, com.yanzhenjie.nohttp.rest.Response<JSONObject> response) {
                super.onSucceed(what, response);
                Log.d(TAG,"返回的数据:"+response.get().toString());
                try {
                    List<Map<String, String>> mList = new ArrayList<Map<String, String>>();
                    JSONObject jsonObject = new JSONObject(response.get().toString());
                    JSONArray jsonArray = jsonObject.getJSONArray(KEY_JSON_DATA);

                    //获取属性分类
                    JSONObject condition = (JSONObject) jsonArray.get(0);
                    JSONArray conditionJSONArray = condition.getJSONArray(KEY_JSON_LF_CONDITION);
                    for (int i = 0 ; i < conditionJSONArray.length() ; i ++){
                        Log.d(TAG,conditionJSONArray.get(i).toString());
                    }
                    //获取列表长度
                    JSONObject listSize = (JSONObject) jsonArray.get(1);
                    int size = Integer.parseInt(listSize.optString(KEY_JSON_LF_LISTSIZE));

                    //获取需要展示的数据
                    JSONObject jsonArrayObject = (JSONObject) jsonArray.get(2);
                    JSONArray msgArray = jsonArrayObject.getJSONArray(KEY_JSON_LF_LISTVAR);

                    //得出总页数
                    if (size <= PAGE_COUNTS ){
                        TOTAL_PAGE = 1;
                    }else {
                        if (size % PAGE_COUNTS == 0 ){
                            TOTAL_PAGE = size/PAGE_COUNTS;
                        }else {
                            TOTAL_PAGE = (size/PAGE_COUNTS) + 1;
                        }
                    }
                    typeList = new ArrayList<>();
                    coumId = new int[msgArray.length()];
                    //将List_id放入数组
                    for (int i = 0; i < msgArray.length(); i++) {
                        JSONObject myjsonObject = (JSONObject) msgArray.get(i);
                        coumId[i] = Integer.parseInt(myjsonObject.get(KEY_FLISTID).toString());
                    }
                    //去除重复元素
                    for (int i = 0; i < coumId.length; i++) {
                        if (!typeList.contains(coumId[i])) {
                            typeList.add(coumId[i]);
                        }
                    }
                    //如果是刷新操作，重新实例一个数据展示List，避免在请求中修改List长度二位通知到adapter的情况产生
                    if (isRefresh)
                        refreshList = new ArrayList<List<showBean>>();
                    //封装数据
                    for (int j = 0; j < typeList.size(); j++) {
                        List<showBean> myList = new ArrayList<showBean>();
                        for (int i = 0; i < msgArray.length(); i++) {
                            JSONObject myjsonObject = (JSONObject) msgArray.get(i);
                            if (Integer.parseInt(myjsonObject.get(KEY_FLISTID).toString()) == typeList.get(j)) {
                                showBean show = new showBean();
                                show.setFxValue(myjsonObject.get(KEY_FXVALUE).toString());
                                show.setFCorresPondingTable(myjsonObject.get(KEY_FCORRESPONDINGTABLE).toString());
                                show.setFyValue(myjsonObject.get(KEY_FYVALUE).toString());
                                show.setFCartogramTypr(myjsonObject.get(KEY_FCARTOGRAMTYPR).toString());
                                show.setFListId(myjsonObject.get(KEY_FLISTID).toString());
                                myList.add(show);
                            }
                        }

                        if (PAGE == 1 && isRefresh == false){
                            showList.add(myList);
                        }

                        else if (PAGE != 1 && isRefresh ==false){
                            Message message = new Message();
                            message.what = 2020;

                            //message.obj = myList;
                            String str=JSON.toJSON(myList).toString();
                            message.obj = str;
                            myHandle.sendMessage(message);
                        }

                        else if(PAGE == 1 && isRefresh ==true){
                            Message message = new Message();
                            message.what = 1197;
                            String str=JSON.toJSON(myList).toString();
                            message.obj = str;
                           // message.obj = myList;
                            myHandle.sendMessage(message);
                        }
                    }
                    if (PAGE == 1 && isRefresh == false){
                        Log.d(TAG,"PAGE == 1");
                        myHandle.sendEmptyMessageDelayed(1,0);
                    }else if (PAGE != 1 && isRefresh ==false){
                        Log.d(TAG,"PAGE == "+PAGE);
                        myHandle.sendEmptyMessageDelayed(2,0);
                    }else if(PAGE == 1 && isRefresh ==true){
                        myHandle.sendEmptyMessageDelayed(3,0);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    Handler myHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    //第一次进入加载数据
                    adapter = new MyListViewAdapter(getActivity(),showList);
                    mListView.setAdapter(adapter);
                    break;
                case 2:
                    //上拉之后加载数据
                    adapter.notifyDataSetChanged(); //数据集变化后,通知adapter
                    mListView.setSelection(PAGE_COUNTS * PAGE - (PAGE_COUNTS+1)); //设置选中项
                    break;
                case 3:
                    adapter.notifyDataSetChanged(); //数据集变化后,通知adapter
                    break;
                case 2020:
                    //加载
                    String jsonStrLoad = msg.obj.toString();
                    List<showBean> list;
                    list = com.alibaba.fastjson.JSONObject.parseArray(jsonStrLoad, showBean.class);

                   // List<showBean> bean= (List<showBean>) msg.obj;
                    adapter.addItem(list);
                    onLoad();
                    break;
                case 1197:
                    //刷新
                   // List<showBean> refreshBean = (List<showBean>) msg.obj;
                    String jsonStrRe = msg.obj.toString();
                    List<showBean> refreshBean;
                    refreshBean = com.alibaba.fastjson.JSONObject.parseArray(jsonStrRe, showBean.class);
                    refreshList.add(refreshBean);
                    adapter.refreshData(refreshList);
                    onLoad();
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
